import re
from collections import defaultdict

# 构建树结构的递归字典
def tree():
    return defaultdict(tree)

# 插入目录项到树中
def insert_into_tree(tree_dict, number_str, title):
    parts = number_str.split('.')
    current = tree_dict
    for i in range(len(parts)):
        key = '.'.join(parts[:i+1])
        if "title" not in current[key]:
            current[key]["title"] = None
            current[key]["children"] = {}
        current = current[key]["children"]
    current[number_str] = {"title": title, "children": {}}

# 解析 markdown 文件构建目录树
def build_tree_from_md(md_path):
    toc_tree = tree()
    pattern = re.compile(r'^(\d+(?:\.\d+)*)(?:\s+)(.+)$')

    with open(md_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            match = pattern.match(line)
            if match:
                number, title = match.groups()
                insert_into_tree(toc_tree, number, title)
    return toc_tree
if __name__ == '__main__':
    build_tree_from_md("D:\\hbyt\\AI智能投标\\典型投标标书目录\\word\\常规目录\\标准目录\\投标文件_技术服务方案部分_邮储银行.md")